package com.hcbd.tdwt.ui.haige.common.fragment;
import android.annotation.SuppressLint;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.DisplayMetrics;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.core.content.ContextCompat;

import com.hcbd.tdwt.R;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.model.GradientColor;
import com.hcbd.tdwt.MainApp;

import com.hcbd.tdwt.base.BaseFragment;
import com.hcbd.tdwt.base.BeidouBoxParams;
import com.pangu.bdsdk2021.entity.terminalthree.BDSnrInfo;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import static android.content.Context.SENSOR_SERVICE;

@SuppressLint("NonConstantResourceId")
@EFragment(R.layout.activity_bd_status_haige)
public class BdStatusFragment extends BaseFragment implements SensorEventListener, MainApp.LocationInfoInterface {
    @ViewById
    TextView title;// 主标题
    @ViewById
    LinearLayout compassIV;// 指南针背景
    @ViewById
    ImageView pointerImg;//针
    @ViewById
    TextView compassDirectionTV;// 方向文本
    @ViewById
    TextView lngTV;// 经度
    @ViewById
    TextView latTV;// 纬度
    @ViewById
    TextView highTV;// 高度
    @ViewById
    TextView cardNumberTV;  // 卡号
    @ViewById
    TextView powerTV;  // 电量
    @ViewById
    TextView signalTV;  // 信号
    @ViewById
    TextView cardFrequencyTV;  // 频度
    @ViewById
    TextView cardLevelTV;  // 等级
    @ViewById
    TextView cardStatusTV;  // 状态
    @ViewById
    BarChart mBarChart;  // 信号统计图
    @ViewById
    RelativeLayout topRL;
    private SensorManager sManager;
    private Sensor mSensorOrientation;
    private int currentDegree=180;
    private List<BarEntry> chartData;
    private List<BarEntry> twoChartData;
    private int width;

    @AfterViews
    protected void init() {
        title.setText("状态");
        chartData = new ArrayList<>();
        twoChartData = new ArrayList<>();
        DisplayMetrics dm = getResources().getDisplayMetrics();
        isRefreshing = true;
        width = dm.widthPixels;
        initChart();
        initChartData();
        initCardMsg();
        sManager = (SensorManager)getActivity().getSystemService(SENSOR_SERVICE);
        mSensorOrientation = sManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
        sManager.registerListener(this, mSensorOrientation, SensorManager.SENSOR_DELAY_UI);
        topRL.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.top_bg_haige));
        initMsgRegister();
        MainApp.getInstance().setLocationInfoInterface(this);
    }

    public void initCardMsg() {
        lngTV.setText(BeidouBoxParams.gpsLongitude);
        latTV.setText(BeidouBoxParams.gpsLatitude);
        highTV.setText(String.valueOf(BeidouBoxParams.gpsAltitude));
        cardNumberTV.setText(BeidouBoxParams.userCardNumber);
        cardFrequencyTV.setText(String.valueOf(BeidouBoxParams.sendFreq));
        cardLevelTV.setText(String.valueOf(BeidouBoxParams.cardType));
        if (BeidouBoxParams.sentWaitSec > 0) {
            cardStatusTV.setText("繁忙");
        } else {
            cardStatusTV.setText("空闲");
        }

        if (BeidouBoxParams.getBdSignal() > 2) {
            signalTV.setText("强");
        } else {
            signalTV.setText("弱");
        }
        if ("E".equals(BeidouBoxParams.ASecretIdentity)) {
            powerTV.setText("加密");
        } else {
            powerTV.setText("非密");
        }

    }


    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true, priority = 1)
    public void eventBus(BDSnrInfo bdSnrInfo) {
        updateChartData();
        if (BeidouBoxParams.getBdSignal() > 1) {
            signalTV.setText("强");
        } else {
            signalTV.setText("弱");
        }
    }

    public void initChartData() {
        chartData.add(new BarEntry(0, BDSnrInfo.obj.s1));
        chartData.add(new BarEntry(1, BDSnrInfo.obj.s2));
        chartData.add(new BarEntry(2, BDSnrInfo.obj.s3));
        chartData.add(new BarEntry(3, BDSnrInfo.obj.s4));
        chartData.add(new BarEntry(4, BDSnrInfo.obj.s5));
        chartData.add(new BarEntry(5, BDSnrInfo.obj.s6));
        chartData.add(new BarEntry(6, BDSnrInfo.obj.s7));
        chartData.add(new BarEntry(7, BDSnrInfo.obj.s8));
        chartData.add(new BarEntry(8, BDSnrInfo.obj.s9));
        chartData.add(new BarEntry(9, BDSnrInfo.obj.s10));
        twoChartData.add(new BarEntry(10, BDSnrInfo.obj.s11));
        twoChartData.add(new BarEntry(11, BDSnrInfo.obj.s12));
        twoChartData.add(new BarEntry(12, BDSnrInfo.obj.s13));
        twoChartData.add(new BarEntry(13, BDSnrInfo.obj.s14));
        twoChartData.add(new BarEntry(14, BDSnrInfo.obj.s15));
        twoChartData.add(new BarEntry(15, BDSnrInfo.obj.s16));
        twoChartData.add(new BarEntry(16, BDSnrInfo.obj.s17));
        twoChartData.add(new BarEntry(17, BDSnrInfo.obj.s18));
        twoChartData.add(new BarEntry(18, BDSnrInfo.obj.s19));
        twoChartData.add(new BarEntry(19, BDSnrInfo.obj.s20));
        twoChartData.add(new BarEntry(20, BDSnrInfo.obj.s21));
        chartData.addAll(twoChartData);
        setWidth(width + width / 2);
        mBarChart.setTouchEnabled(false);
    }

    //更新图表数据
    public void updateChartData() {
        setXY(0, 0, BDSnrInfo.obj.s1);
        setXY(1, 1, BDSnrInfo.obj.s2);
        setXY(2, 2, BDSnrInfo.obj.s3);
        setXY(3, 3, BDSnrInfo.obj.s4);
        setXY(4, 4, BDSnrInfo.obj.s5);
        setXY(5, 5, BDSnrInfo.obj.s6);
        setXY(6, 6, BDSnrInfo.obj.s7);
        setXY(7, 7, BDSnrInfo.obj.s8);
        setXY(8, 8, BDSnrInfo.obj.s9);
        setXY(9, 9, BDSnrInfo.obj.s10);
        setXY(10, 10, BDSnrInfo.obj.s11);
        setXY(11, 11, BDSnrInfo.obj.s12);
        setXY(12, 12, BDSnrInfo.obj.s13);
        setXY(13, 13, BDSnrInfo.obj.s14);
        setXY(14, 14, BDSnrInfo.obj.s15);
        setXY(15, 15, BDSnrInfo.obj.s16);
        setXY(16, 16, BDSnrInfo.obj.s17);
        setXY(17, 17, BDSnrInfo.obj.s18);
        setXY(18, 18, BDSnrInfo.obj.s19);
        setXY(19, 19, BDSnrInfo.obj.s20);
        setXY(20, 20, BDSnrInfo.obj.s21);
        updateChart();
        setData(chartData);
    }

    //更新图表
    public void updateChart() {
        XAxis xAxis = mBarChart.getXAxis();
        xAxis.setGranularity(1f);
        xAxis.setLabelCount(BeidouBoxParams.horizontalAxis);
        YAxis leftAxis = mBarChart.getAxisLeft();
        leftAxis.setAxisMinimum(0f);
        leftAxis.setAxisMaximum(BeidouBoxParams.verticalAxis);
    }

    //初始化图表
    private void initChart() {
        //设置表格上的点，被点击的时候，的回调函数
        mBarChart.setDrawBarShadow(false);
        mBarChart.setDrawValueAboveBar(true);
        mBarChart.getDescription().setEnabled(false);
        mBarChart.setPinchZoom(false);
        mBarChart.setDrawGridBackground(false);
        XAxis xAxis = mBarChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        xAxis.setGridColor(R.color.light_blue);
        xAxis.setTextColor(getResources().getColor(R.color.black));
        xAxis.setGranularity(1f);
        xAxis.setLabelCount(BeidouBoxParams.horizontalAxis);
        mBarChart.getAxisRight().setEnabled(false);
        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                return "C" + (int) (value + 1);
            }
        });
        YAxis leftAxis = mBarChart.getAxisLeft();
        leftAxis.setLabelCount(4, false);
        leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        leftAxis.setAxisMinimum(0f);
        leftAxis.setTextColor(getResources().getColor(R.color.black));
        leftAxis.setAxisMaximum(BeidouBoxParams.verticalAxis);
        mBarChart.setTouchEnabled(false);
    }

    //设置图表宽度
    private void setWidth(int width) {
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mBarChart.getLayoutParams();//获取当前控件的布局对象
        params.width = width;//设置当前控件布局的高度
        mBarChart.setLayoutParams(params);//将设置好的布局参数应用到控件中
    }

    public void setXY(int index, int x, int y) {
        chartData.get(index).setX(x);
        chartData.get(index).setY(y);
    }

    //设置数据
    private void setData(List<BarEntry> list) {
        BarDataSet set1;
        if (mBarChart.getData() != null && mBarChart.getData().getDataSetCount() > 0) {
            set1 = (BarDataSet) mBarChart.getData().getDataSetByIndex(0);
            set1.setValues(list);
            mBarChart.getData().notifyDataChanged();
        } else {
            set1 = new BarDataSet(list, "");
            int bottomColor = ContextCompat.getColor(this.getContext(), R.color.light_blue);
            //顶部渐变色
            int topColor = ContextCompat.getColor(this.getContext(), R.color.blue);
            //2.    新建List存储渐变色
            List<GradientColor> gradientColors = new ArrayList<>();
            gradientColors.add(new GradientColor(bottomColor, topColor));

            //3.    添加颜色List到BarDataSet
            //set类型是BarDataSet
            set1.setGradientColors(gradientColors);
            set1.setValueTextColor(getResources().getColor(R.color.black));
            set1.setValueFormatter(new ValueFormatter() {
                @Override
                public String getFormattedValue(float value) {
                    return String.valueOf((int) value);
                }
            });
            ArrayList<IBarDataSet> dataSets = new ArrayList<>();
            dataSets.add(set1);
            BarData data = new BarData(dataSets);
            data.setValueTextSize(10f);
            data.setBarWidth(0.4f);
            //设置数据
            mBarChart.setData(data);
        }
        //    mBarChart.notifyDataSetChanged();
        mBarChart.invalidate();
    }

    //指针移动
    public void roteCompass(int degree) {
        if (degree == 0|| currentDegree==degree) {
            return;
        }
        RotateAnimation ra = new RotateAnimation(currentDegree,degree, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        ra.setInterpolator(new LinearInterpolator());
        ra.setDuration(200);//动画时间200毫秒
        ra.setFillAfter(true);//设置动画结束后的保留状态
        compassIV.startAnimation(ra);
        currentDegree = degree;

        int mAngla = Math.abs(degree);
        if (mAngla > 336 || mAngla <= 23) {
            compassDirectionTV.setText(MessageFormat.format("{0}°北",mAngla));
        } else if (mAngla <= 68) {
            compassDirectionTV.setText(String.format("%s°东北", mAngla));
        } else if (mAngla <= 111) {
            compassDirectionTV.setText(String.format("%s°东", mAngla));
        } else if (mAngla <= 156) {
            compassDirectionTV.setText(String.format("%s°东南", mAngla));
        } else if (mAngla <= 202) {
            compassDirectionTV.setText(String.format("%s°南", mAngla));
        } else if (mAngla <= 246) {
            compassDirectionTV.setText(String.format("%s°西南", mAngla));
        } else if (mAngla <= 292) {
            compassDirectionTV.setText(String.format("%s°西", mAngla));
        } else {
            compassDirectionTV.setText(String.format("%s°西北",mAngla));
        }
    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        //保持设备水平，使用水平传感器
        if(sensorEvent.sensor.getType()==Sensor.TYPE_ORIENTATION){
            roteCompass(-(int) sensorEvent.values[0]);
        }

    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }

    @Override
    public void LocationInfo() {
        if (lngTV != null) {
            lngTV.setText(BeidouBoxParams.gpsLongitude);
            latTV.setText(BeidouBoxParams.gpsLatitude);
            highTV.setText(String.valueOf(BeidouBoxParams.gpsAltitude));
        }
    }



    @Override
    public void onPause() {
        if (sManager != null) {
            sManager.unregisterListener(this);
        }
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        if(sManager!=null) {
            sManager.registerListener(this, mSensorOrientation, SensorManager.SENSOR_DELAY_UI);
        }
    }

    @Override
    public void  onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(hidden){
            //不可见
            hideInputKeyBord();
            sManager.unregisterListener(this);
            EventBus.getDefault().unregister(this);
        }else{
            LocationInfo();
            MainApp.getInstance().setLocationInfoInterface(this);
            sManager.registerListener(this, mSensorOrientation, SensorManager.SENSOR_DELAY_UI);
            initMsgRegister();
            initCardMsg();
        }
    }
}
